import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import {Input} from "antd";
import {useTranslation} from "react-i18next";
import GlobalIcon from "../../global/GlobalIcon.tsx";
import {getObjByRule, getRepeat, importComponent, isArray} from "../../utils";
import {coreDispatch} from "../../utils/StoreUtil.tsx";
import useStateRef from "../../customUse/useStateRef.tsx";
import SelectModal from "../../component/modal/select/SelectModal.tsx";

interface InputModalProps {
    menuId: string,
    disabled?: boolean | undefined,
    value: any,
    ds: any,
    search?: string | undefined,
    title?: string | undefined,
    rowSelection?: 'single' | 'multiple' | undefined,
    tableApi: any,
    viewName: string,
    modalCom?: any,
    modalProps?: any,
    comProps?: any,
    format?: any,
    joinValue?: string | undefined,
    onChange: Function
}

const InputModal: FC<InputModalProps> = (props) => {
    const {t} = useTranslation();

    const optionRef = useRef();

    const [isClose, setIsClose] = useState<boolean>(false),
        [option, setOption] = useStateRef(null, optionRef);

    useEffect(() => {
        if (optionRef.current && optionRef.current.value !== props.value) {
            setOption({
                text: null,
                value: props.value
            });
            !props.value && setIsClose(false);
        }
    }, [props.value]);

    useEffect(() => {
        const {ds = {}}: { ds: any } = props;
        if (optionRef.current && optionRef.current.value === ds.value) {
            setOption(optionRef.current);
        } else {
            setOption({
                text: ds.text,
                value: ds.value
            });
            if (isArray(ds.value) && ds.value.length > 0) {
                setIsClose(true);
            } else {
                ds.value ? setIsClose(true) : setIsClose(false);
            }
        }
    }, [props.ds]);

    const showModal = useCallback(async () => {
        const {
            menuId,
            search,
            title = "pSelectLeastOne",
            rowSelection = "single",
            ds,
            leftApi,
            tableApi,
            viewName,
            modalCom,
            modalProps = {},
            comProps = {},
            disabled = false
        }:
            {
                menuId: string,
                search?: string | undefined,
                title?: string | undefined,
                rowSelection?: 'single' | 'multiple' | undefined,
                ds: any,
                leftApi: any,
                tableApi: any,
                viewName: string,
                modalCom?: any,
                modalProps?: any,
                comProps?: any,
                disabled?: boolean | undefined,
            } = props;
        let Com = SelectModal;
        if (disabled) {
            return null;
        }
        if (modalCom) {
            Com = await importComponent(modalCom)
        }
        coreDispatch("modalReducer/createModal", {
            key: "select" + modalCom + Math.random(),
            modalProps: {
                title: t(title),
                width: 1200,
                ...modalProps
            },
            component: Com,
            comProps: {
                menuId,
                ds,
                selectDataIds: isArray(option.value) ? option.value : [option.value],
                search,
                leftApi,
                tableApi,
                rowSelection,
                viewName,
                ...comProps
            },
            onFinish: (result: any) => {
                if (result.data) {
                    if (rowSelection === "single") {
                        setInputValue(result.data[0]);
                    } else {
                        setInputValue(result.data);
                    }
                }
            }
        })
    }, [props, option]);

    const setInputValue: Function = useCallback((opt: any) => {
        const {format = {id: "id", name: "zhCn|usEn|ptBr"}, joinValue = ","}: {
            format?: any | undefined,
            joinValue?: string | undefined
        } = props;
        let newOpt: any;
        if (isArray(opt)) {
            opt = opt.map((item: any) => getObjByRule(item, {id: "id", name: "zhCn|usEn|ptBr", ...format}, true))
            opt = getRepeat(opt);
            newOpt = {value: opt.map((item: any) => item.id), text: opt.map((item: any) => item.name).join(joinValue)};
        } else {
            opt = getObjByRule(opt, {id: "id", name: "zhCn|usEn|ptBr", ...format}, true)
            newOpt = {value: opt.id, text: opt.name};
        }
        setOption(newOpt);
        setIsClose(true);
        props.onChange && props.onChange(newOpt.value || "");
    }, []);

    const clearValue: Function = useCallback(() => {
        if (props.disabled) {
            return
        }
        setOption({
            text: null,
            value: []
        });
        props.onChange && props.onChange(null);
        setIsClose(false);
    }, [props]);

    const getSuffix = useMemo(() => {
        return (<span>
            {isClose ? (<span onClick={() => clearValue()}><GlobalIcon name={"icon-close"}/></span>) : (
                <span onClick={showModal} style={{cursor: 'pointer'}}>{t("selectInput")}</span>)}
        </span>)
    }, [props, isClose, option]);


    const renderInputModal = useMemo(() => {
        if (!option) {
            return null;
        }
        return (
            <Input
                key='showInput'
                disabled={props.disabled}
                readOnly={true}
                value={option.text}
                suffix={getSuffix}
                onClick={showModal}
            />
        )
    }, [props, option]);

    return (renderInputModal);
};

export default InputModal;